package Control;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 
 * @author stephenbwilliamson
 */
public class DataConnection {

	private Connection conn;
	private static DataConnection instance = null;

	protected DataConnection() {
		// Exists only to defeat instantiation.
	}

	public static DataConnection getInstance() {
		if (instance == null) {
			instance = new DataConnection();
		}
		return instance;
	}

	public boolean tryConnection(String server, String database,
			String username, String password) {
		String connectionString = "jdbc:mysql://" + server + "/" + database;

		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			conn = DriverManager.getConnection(connectionString, username,
					password);
			System.out.println("Database connection established");
		} catch (Exception e) {
			System.err
					.println("Database connection failed : " + e.getMessage());
		}

		if (conn != null) {
			return true;
		}
		return false;
	}

	public ResultSet executeQuery(String sqlStatement) {
		if (!activeConnection())
			tryConnection("isplice.csc.ncsu.edu", "splice_seq", "guest",
					"rnaseq_vis");

		ResultSet result = null;

		try {
			Statement cs = conn.createStatement();
			result = cs.executeQuery(sqlStatement);

		} catch (SQLException e) {
			System.err.println("Error executing sql statement : " + e);
		}

		return result;
	}

	public boolean activeConnection() {
		return conn != null;
	}

	public Connection getConn() {
		return conn;
	}

	public void closeConnection() {
		try {
			if (!conn.isClosed()) {
				conn.close();
				conn = null;
			}
		} catch (Exception e) {
			System.err.println("Can't close the connection to the database: "
					+ e.getMessage());
		}
	}
}
